今天來練習在本機使用 Node.js 應用程式操作Azure Cache for Redis,以便後續可從前幾日建立的Azure Functuons 中來讓Webhook存取Cache。
首先在建立一個資料夾並在終端機輸入 npm init,並在資料夾下新增一個index.js檔案
$ npm init
$ touch index.js
完成後資料夾中會有package.json與index.js檔案
終端機輸入 npm install --save redis & npm install --save bluebird
$ npm install --save redis
$ npm install --save bluebird
可以使用redis module撰寫程式了,修改index.js為下列code
const redis = require("redis");
const bluebird = require("bluebird");
const REDISCACHEHOSTNAME = '<YOUR_AZURE_REDIS_REDISCACHEHOSTNAME>'
const REDISCACHEKEY = '<YOUR_AZURE_REDIS_REDISCACHEKEY>'
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
async function testCache() {
// Connect to the Azure Cache for Redis over the TLS port using the key.
const cacheConnection = redis.createClient(6380, REDISCACHEHOSTNAME,
{ auth_pass: REDISCACHEKEY, tls: { servername: REDISCACHEHOSTNAME } });
// Perform cache operations using the cache connection object...
// Simple PING command
console.log("\nCache command: PING");
console.log("Cache response : " + await cacheConnection.pingAsync());
// Simple get and put of integral data types into the cache
console.log("\nCache command: GET Message");
console.log("Cache response : " + await cacheConnection.getAsync("Message"));
console.log("\nCache command: SET Message");
console.log("Cache response : " + await cacheConnection.setAsync("Message",
"Hello! The cache is working from Node.js!"));
// Demonstrate "SET Message" executed as expected...
console.log("\nCache command: GET Message");
console.log("Cache response : " + await cacheConnection.getAsync("Message"));
// Get the client list, useful to see if connection list is growing...
console.log("\nCache command: CLIENT LIST");
console.log("Cache response : " + await cacheConnection.clientAsync("LIST"));
}
這邊會用到REDISCACHEHOSTNAME(主機名稱)與REDISCACHEKEY(存取金鑰)
還記得我們昨天建立的Azure Redis嗎?這些資訊在Azure入口網站登入後選取建立的Redis Cache後點選
存取金鑰與屬性複製取得如下圖:
還沒建立Azure Redis的朋友可以參考-Day [13] Azure Cache for Redis-建置
在終端機輸入node index.js執行程式
$ node index.js
測試成功明天,將在明天將Azure Functions上操作Azure Cache for Redis。